package oauth.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import oauth.constant.MyConstants;
import oauth.model.AccessToken;
import oauth.model.OAuthResponse;
import oauth.model.RefreshToken;
import oauth.utils.DateUtils;
import oauth.utils.EBayEnvironment;
import oauth.utils.OAuth2Api;

@Component
public class AutoTask {

	@Scheduled(fixedRate = 10000)
	public void autoRefreshToken() {
		System.out.println("刷新token");
		Map<String, RefreshToken> refreshTokenMap = MyConstants.refreshTokenMap;
		Set<String> keySet = refreshTokenMap.keySet();
		if(keySet!=null) {
			for (String key : keySet) {
				 System.out.println("缓存刷新TOKEN账号"+key);
				AccessToken oldAccessToken = MyConstants.accessTokenMap.get(key);
				boolean nendRefreshToken = DateUtils.isNendRefreshToken(oldAccessToken.getExpiresOn());
				if(nendRefreshToken) {
					OAuth2Api oauth2Api = new OAuth2Api();
					List<String> scopeList = new ArrayList<>();
					scopeList.add("https://api.ebay.com/oauth/api_scope");
					scopeList.add("https://api.ebay.com/oauth/api_scope/sell.finances");
					scopeList.add("https://api.ebay.com/oauth/api_scope/sell.fulfillment");
					scopeList.add("https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly");
					try {
						OAuthResponse oauth2Response = oauth2Api.refreshToken(EBayEnvironment.PRODUCTION, scopeList, MyConstants.refreshTokenMap.get(key).getToken());
						System.out.println(oauth2Response);
						AccessToken accessToken = oauth2Response.getAccessToken().get();
						System.out.println(key+"刷新后的"+accessToken.getToken());
						System.out.println(key+"刷新后的"+accessToken.getExpiresOn());
						System.out.println(key+"刷新后的"+accessToken.getExpiresIn());
					//	RefreshToken refreshToken = oauth2Response.getRefreshToken().get();
						MyConstants.accessTokenMap.put(key, accessToken);
						//refreshTokenMap.put(key, refreshToken);
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			
		}
		
		
	}
}
